import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class PutawayScreen extends StatefulWidget {
  const PutawayScreen({super.key});

  @override
  _PutawayScreenState createState() => _PutawayScreenState();
}

class _PutawayScreenState extends State<PutawayScreen> {
  // 定义文本样式常量
  static const double _baseFontSize = 13.0;
  static const double _smallFontSize = 12.0;
  static const double _buttonFontSize = 14.0;
  
  bool _isLoading = false;
  bool _isReadOnly = false;
  bool _showSelectionList = false; // 控制是否显示选择列表
  int? _selectedIndex; // 当前选中的索引
  List<dynamic> _putawayList = []; // 存储返回的数据列表

  final _equipmentController = TextEditingController();
  int? warehouseId;
  late double _fontScale;
  String? loadNumber;
  int? loadId;

  @override
  void initState() {
    super.initState();
    _fetchPutawayDetails();
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    
    // 获取屏幕尺寸信息
    final screenSize = MediaQuery.of(context).size;
    
    // 计算字体缩放比例 (基于屏幕宽度)
    final double scaleFactor = screenSize.width < 600 
        ? (screenSize.width / 600).clamp(0.85, 1.0) 
        : 1.0;

    // 确定输入框是否只读（有数据时只读）
    final isInputReadOnly = _putawayList.isNotEmpty || _isReadOnly;
    
    // 确定OK按钮是否可用（有数据时需选中条目才可用）
    final isButtonEnabled = _putawayList.isEmpty
        ? !_isLoading // 无数据时只需不加载即可
        : !_isLoading && _selectedIndex != null; // 有数据时需要选中条目

    return Scaffold(
      appBar: AppBar(
        title: Text('Putaway', style: TextStyle(fontSize: 18 * _fontScale)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back,color: Color.fromARGB(255, 255, 255, 255)),
          onPressed: () => Navigator.pushNamed(context,'/inbound'),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      // 添加GestureDetector监听空白区域点击
      body: GestureDetector(
        // 点击空白区域时取消所有输入框焦点
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        // 确保空白区域也能响应点击事件
        behavior: HitTestBehavior.opaque,
        child: Padding(
          padding: EdgeInsets.all(32 * scaleFactor),  // 响应式内边距
          child: Column(
            children: [
              TextField(
                readOnly: isInputReadOnly,
                controller: _equipmentController,
                decoration: InputDecoration(
                  labelText: 'Equipment',
                  labelStyle: TextStyle(fontSize: _baseFontSize * scaleFactor),
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.handyman),
                  contentPadding: EdgeInsets.symmetric(
                    vertical: 16 * scaleFactor, 
                    horizontal: 12 * scaleFactor
                  ),
                ),
                style: TextStyle(fontSize: _baseFontSize * scaleFactor),
                onTap: (){
                  // 点击时全选内容
                  if (_equipmentController.text.isNotEmpty) {
                    _equipmentController.selection = TextSelection(
                      baseOffset: 0,
                      extentOffset: _equipmentController.text.length,
                    );
                  }
                },
              ),
              SizedBox(height: 16 * scaleFactor),
              
              // 显示选择列表（当有数据时）
              if (_showSelectionList)
                Expanded(
                  child: ListView.builder(
                    itemCount: _putawayList.length,
                    itemBuilder: (context, index) {
                      final item = _putawayList[index];
                      final isSelected = _selectedIndex == index;
                      
                      return Card(
                        elevation: 2,
                        margin: EdgeInsets.symmetric(vertical: 4 * scaleFactor),
                        child: Container(
                          color: isSelected ? Colors.green[50] : null,
                          child: ListTile(
                            title: Text(
                              '${item['load_number'] ?? 'No Load Number' }            ${item['shipment']['order_number']?? item['shipment']['shipment_code']??'' }',
                              style: TextStyle(
                                fontSize: _baseFontSize * scaleFactor,
                                color: isSelected ? Colors.green : Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            subtitle: Text(
                              'Equip: ${item['equipment']}     Created: ${item['create_datetime']?.split(' ').first ?? 'N/A'}',
                              style: TextStyle(
                                fontSize: _smallFontSize * scaleFactor,
                                color: isSelected ? Colors.green : Colors.black,
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                // 如果点击已选中的项，则取消选中
                                _selectedIndex = isSelected ? null : index;
                              });
                            },
                          ),
                        ),
                      );
                    },
                  ),
                ),
              
              SizedBox(height: 30 * scaleFactor),
              SizedBox(
                width: double.infinity,
                height: 50 * scaleFactor,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF008363),
                    disabledBackgroundColor: Colors.grey,
                  ),
                  onPressed: isButtonEnabled
                      ? () {
                          if (_putawayList.isNotEmpty) {
                            // 有数据时传递选中的条目
                            Navigator.pushNamed(
                              context,
                              '/inbound/load-task',
                              arguments: {
                                'loadTaskData':_putawayList[_selectedIndex!],
                                'loadNumber':_putawayList[_selectedIndex!]['load_number'],
                                'loadId':_putawayList[_selectedIndex!]['id'],
                              },
                            );
                          } else {
                            // 无数据时使用输入框内容
                            _handleSubmitted(
                              _equipmentController.text,
                            );
                          }
                        }
                      : null,
                  child: _isLoading
                      ? SizedBox(
                          width: 20 * scaleFactor,
                          height: 20 * scaleFactor,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Colors.white,
                          ),
                        )
                      : Text(
                          'OK',
                          style: TextStyle(
                            fontSize: _buttonFontSize * scaleFactor, 
                            color: Colors.white
                          ),
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 获取上架详情数据
  Future<void> _fetchPutawayDetails() async {
    if (!mounted) return;
    
    setState(() {
      _isLoading = true;
    });

    try {
      final response = await _getLoadList();
      if (response['code'] == 2000) {
        final dataList = response['data'] as List<dynamic>;
        debugPrint('dataList--$dataList');
        setState(() {
          _putawayList = dataList;
          _showSelectionList = dataList.isNotEmpty;
          
          // 初始不选中任何数据
          _selectedIndex = null;
        });
      } else if (response['code'] == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
      } else {
        throw Exception('${response['msg']}');
      }
    } catch (e) {
      MessageBox.showMessageBox(context,e,isError:true);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  // API调用封装
  Future<Map<String, dynamic>> _getLoadList() async {
    final apiUrl = ApiService.baseURL + ApiService.undoLoad;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }

    final response = await http.get(
      Uri.parse(apiUrl),
      headers: {
        'Authorization': 'JWT $accessToken',
        'x-warehouse-id': '$warehouseId',
        'x-timezone': 'America/Los_Angeles',
        'Content-Type': 'application/json',
        'X-Client-Type': 'app'
      },
    );

    if (response.statusCode == 200) {
      return json.decode(utf8.decode(response.bodyBytes));
    } else {
      throw Exception('HTTP Error: ${response.statusCode}');
    }
  }

  // 处理提交
  void _handleSubmitted(String equipment) async {
    if (_isLoading) return;
    if(equipment.isEmpty){
      MessageBox.showMessageBox(context,'Equipment can`t be null.',isError:true);
      return;
    }
    // if(loadNumber.isEmpty){
    //   MessageBox.showMessageBox(context,'Load can`t be null.',isError:true);
    //   return;
    // }
    setState(() {
      _isLoading = true;
      _isReadOnly = true;
    });

    try {
      if (!mounted) return;
      final details = await _createLoad(
        equipment: equipment,
      );
      
      Navigator.pushNamed(
        context,
        '/inbound/load-task',
        arguments: {
          'loadTaskData':details,
          'loadNumber':loadNumber,
          'loadId':loadId,
        },
      );
    } catch (e) {
      if (!mounted) return;
      MessageBox.showMessageBox(context,e,isError:true);
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isReadOnly = false;
        });
      }
    }
  }

  // 调用API获取详情数据
  Future<Map<String, dynamic>> _createLoad({required String equipment}) async {
    var apiUrl = ApiService.baseURL + ApiService.createLoad;

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }

    final requestBody = {
      'id': null,
      'equipment': equipment,
      // 'load_number': loadNumber,
      'warehouse': warehouseId
    };
    
    try {
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody)
      );
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          apiUrl = ApiService.baseURL + ApiService.fetchLoad;
          setState(() {
            loadNumber = jsonData['data']['load_number']??'';
            loadId = jsonData['data']['id']??'';
          });
          final responsedata = await http.get(
            Uri.parse(apiUrl + loadNumber!),
            headers: {
              'Authorization': 'JWT $accessToken',
              'x-warehouse-id': '$warehouseId',
              'x-timezone': 'America/Los_Angeles',
              'Content-Type':'application/json',
              'X-Client-Type':'app'
            },
          );
          String responseBody = utf8.decode(responsedata.bodyBytes);
          Map<String, dynamic> responseData = json.decode(responseBody);
          return responseData['data'];
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }
}
